/* 
 * Handles functions used on the Caterers UI
 */

var caterers = {

    init: function(){
        this.bindGridItems();
        this.bindStaticElements();
        this.bindSearchField();
    },
    
    bindGridItems: function() {
        $(".fullwidth input.star").rating("disable");
        
        $(".fullwidth tbody tr").click(function() {
            var url = $(this).data('url');
            
            $.get(url, function(data) {
                $(".details_block").html(data);
                $(".details_block input.star").rating();
                $(".details_block input.star").rating('disable');
            });
        });
        
        $(".fullwidth tbody tr:first").addClass('selected').click();
        
        
        $(".edit_link").data({
            height: 550,
            'load-callback': function() {
                $("#general_dialog input.star").rating();
            },
            'callback': function(data) {
                $(".fullwidth tr.selected .caterer_name").html( data.Caterer.name );
                $(".fullwidth tr.selected").click();
            }
        });
        
        $('.del').bind('click',function(e){
            e.preventDefault();
            
            var $this = $(this);
            var id = $this.attr("data-id");
            
            if( id != null && confirm("Are You Sure You Want To Delete This Record(s)?") ){
                var url = $this.attr('del_url');
                $.get(url, function() {
                    $this.parents('tr').remove();
                });
            }
        });
    },
    
    bindStaticElements: function() {
        
        $("#add_caterer").data({
            height: 550,
            'load-callback': function() {
                $("#general_dialog input.star").rating();
            },
            'callback': function() {
                window.history.go(0);
            }
        });
    },
    
    bindSearchField: function() {
        $("#search_field").keyup(function(e) {
            
            if( e.keyCode == 13 ) {
                var url = $(this).data('url');
                var params = "field=" + $(this).val() + "&term=" + $("#search_by").val();
            
                $.post(url, params, function(data) {
                    $(".master_block").html(data);
                    caterers.bindGridItems();
                });
            }
        });
    }
};

$(document).ready(function(){
    caterers.init();
});